
<template>
  <div class="view-container">
    <div class="app-title-container title-position">
      <modules-title title-name="自研立项">
        <template slot="btn">
          <!-- <el-checkbox v-model="relatedTopics">关联项目课题</el-checkbox> -->
          <el-button
            v-hasPermi="{ v: ['project:my:add'] }"
            style="margin-left: 20px"
            type="primary"
            @click="createProject"
          >创建自研立项
          </el-button>
        </template>
      </modules-title>
    </div>
    <div class="main-content-container">
      <el-form
        v-show="showSearch"
        ref="queryForm"
        class="filter-form"
        :model="queryParams"
        :inline="true"
        label-width="68px"
      >
        <el-form-item
          label=""
          style="margin-right: 40px"
        >
          <el-select
            v-model="queryParams.select_type"
            placeholder="请选择"
            size="small"
            @change="filterChange"
          >
            <el-option
              v-for="fr in categoryOption"
              :key="fr.id"
              :label="fr.label"
              :value="fr.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="立项状态"
          style="margin-right: 40px"
        >
          <el-select
            v-model="queryParams.info_status"
            placeholder="请选择状态"
            size="small"
            @change="filterChange"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.id"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="项目类型"
          style="margin-right: 40px"
        >
          <el-select
            v-model="queryParams.project_type_id"
            placeholder="请选择项目类型"
            clearable
            :style="{ width: '100%' }"
            @change="filterChange"
          >
            <el-option
              v-for="(item, index) in projectTypeOptions"
              :key="index"
              :label="item.dict_val"
              :value="item.id"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="申请时间"
          style="margin-right: 40px"
        >
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="dateRangeChang"
          />
        </el-form-item>
        <el-form-item
          label="关键字"
          style="margin-right: 40px"
        >
          <el-input
            v-model="queryParams.select_str"
            clearable
            placeholder="请输入项目名称"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="small"
            @click="handleSearch"
          >搜索
          </el-button>
          <el-button
            plain
            size="small"
            @click="resetQuery"
          >重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        border
        size="medium"
        :data="tableList"
        :cell-style="tableCellStyle"
        row-key="id"
        @row-click="tableRowClick"
      >
        <el-table-column
          label="申请项目名称"
          align="left"
          header-align="center"
          prop="project_name"
          width="240px"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="申请项目类型"
          align="center"
          prop="project_type"
        />
        <el-table-column
          label="申报类别"
          align="center"
          prop="apply_type"
        />
        <el-table-column
          label="药物类别"
          align="center"
          prop="medical_type"
        />
        <el-table-column
          label="申请人"
          align="center"
          prop="creator_name"
        />
        <el-table-column
          label="申请时间"
          align="center"
          prop="created_at"
        />
        <el-table-column
          label="状态"
          align="center"
          prop="info_status"
        >
          <template slot-scope="scope">
            <div>
              <p
                v-if="scope.row.info_status == 0"
                class="status-common"
              >
                草稿
              </p>
              <p
                v-else-if="scope.row.info_status == 1"
                class="status-common"
              >
                调研中
              </p>
              <p
                v-else-if="scope.row.info_status == 2"
                class="status-common"
              >
                评估中
              </p>
              <p
                v-else-if="scope.row.info_status == 3"
                class="status-common"
              >
                决议审批中
              </p>
              <p
                v-else-if="scope.row.info_status == 4"
                class="status-common"
              >
                不予立项
              </p>
              <p
                v-else-if="scope.row.info_status == 5"
                class="status-common"
              >
                暂时搁置
              </p>
              <p
                v-else-if="scope.row.info_status == 6"
                class="status-common"
              >
                同意立项
              </p>
              <p
                v-else-if="scope.row.info_status == 7"
                class="status-common"
              >
                立项审批中
              </p>
              <p
                v-else-if="scope.row.info_status == 8"
                class="status-common"
              >
                拒绝
              </p>
              <p
                v-else-if="scope.row.info_status == 9"
                class="status-common"
              >
                通过
              </p>
              <p
                v-else-if="scope.row.info_status == 10"
                class="status-common"
              >
                已立项审批
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="left"
          header-align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <div class="btn-container">
              <el-button
                v-if="scope.row.info_status == 0"
                size="medium"
                type="text"
                @click="handleUpdate(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="scope.row.info_status == 0"
                size="medium"
                type="text"
                @click="startResearch(scope.row)"
              >
                启动调研
              </el-button>
              <el-button
                v-hasPermi="{
                  v: ['project:my:submitReport'],
                  isF: scope.row.info_status == 1 && scope.row.isJoin && !scope.row.isSubmit,
                }"
                size="medium"
                type="text"
                @click="submitReport(scope.row)"
              >
                填写调研报告
              </el-button>
              <el-button
                v-if="scope.row.info_status == 2 && scope.row.isCreator"
                size="medium"
                type="text"
                @click="startMeeting(scope.row)"
              >
                发起会议
              </el-button>
              <el-button
                v-if="scope.row.info_status == 2 && scope.row.isCreator"
                size="medium"
                type="text"
                @click="returnResearchOperation(scope.row)"
              >
                回退调研
              </el-button>
              <el-button
                v-if="scope.row.info_status == 2 && scope.row.isCreator"
                size="medium"
                type="text"
                @click="applyResolutionOperation(scope.row)"
              >
                申请决议
              </el-button>
              <!-- <el-button
                v-hasPermi="{
                  v: ['project:my:audit'],
                  isF: scope.row.info_status == 3 ? true : false,
                }"
                size="medium"
                type="text"
                @click="handleAudit(scope.row)"
              >
                决议审批</el-button> -->
              <el-button
                v-if="scope.row.info_status == 5 && scope.row.isCreator"
                size="medium"
                type="text"
                @click="returnResearchOperation(scope.row)"
              >
                启动调研
              </el-button>
              <el-button
                v-hasPermi="{
                  v: ['project:my:printLookInfo'],
                  isF: scope.row.info_status == 6 || scope.row.info_status == 10,
                }"
                size="medium"
                type="text"
                @click="printLookInfo(scope.row)"
              >
                打印尽调表
              </el-button>
              <!-- <el-button
                v-hasPermi="{
                  v: ['project:my:printLookInfo'],
                  isF: scope.row.info_status == 6 || scope.row.info_status == 10,
                }"
                size="medium"
                type="text"
                @click="exportLookInfo(scope.row)"
              >
                导出尽调表
              </el-button> -->
              <el-button
                v-hasPermi="{
                  v: ['project:my:submitProjectApproval'],
                  isF: scope.row.info_status == 6 ? true : false,
                }"
                size="medium"
                type="text"
                @click="submitProjectApproval(scope.row)"
              >
                发起立项审批
              </el-button>
              <!-- <el-button
                v-hasPermi="{
                  v: ['project:my:projectApproval'],
                  isF: scope.row.info_status == 7 ? true : false,
                }"
                size="medium"
                type="text"
                @click="projectApprovalOperation(scope.row)"
              >
                立项审批
              </el-button> -->
              <el-button
                v-hasPermi="{
                  v: ['project:my:printApproval'],
                  isF: scope.row.info_status == 9 ? true : false,
                }"
                size="medium"
                type="text"
                @click="printApproval(scope.row)"
              >
                打印立项审批表</el-button>
              <!-- <el-button
                v-hasPermi="{ v: ['project:my:detail'], isF: true }"
                class="text-btn-yellow"
                size="medium"
                type="text"
                @click="details(scope.row)"
              >
                详情</el-button> -->
              <el-button
                v-if="scope.row.info_status == 0"
                class="text-btn-red"
                size="medium"
                type="text"
                @click="handleDelete(scope.row)"
              >
                删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        style="display: flex; justify-content: flex-end"
        :total="total"
        :page.sync="queryParams.pager.skip"
        :limit.sync="queryParams.pager.limit"
        @pagination="getList"
      />
    </div>
    <!-- 决议审批 -->
    <audit-dialog
      ref="auditDialog"
      :project-id="currentId"
      @evaluationSuccess="evaluationSuccess"
    />
    <!-- 发起会议 -->
    <start-meeting-dialog ref="startMeetingDialog" />
    <!-- 关联项目课题 -->
    <requirement-list-dialog ref="requirementListDialog" />
    <!-- 立项审批 -->
    <project-approval-dialog
      ref="projectApprovalDialog"
      :project-id="currentId"
      @projectApprovalSuccess="projectApprovalSuccess"
    />
    <!-- 回退调研 -->
    <return-look-info-dialog
      ref="returnLookDialog"
      @returnSuccess="backSuccess"
    />
    <!-- 打印尽调表 -->
    <vue-easy-print
      v-if="detailData"
      ref="printLookInfo"
    >
      <template slot-scope="func">
        <div id="print-template">
          <look-info-print
            :detail-data="detailData"
            :setting-list="settingList"
          />
        </div>
      </template>
    </vue-easy-print>
    <!-- 尽调表导出 -->
    <vue-html2pdf
      v-if="detailData"
      ref="html2Pdf"
      :show-layout="false"
      :float-layout="true"
      :enable-download="true"
      :preview-modal="false"
      :html-to-pdf-options="pdfOptions"
      :paginate-elements-by-height="1754"
      pdf-content-width="100%"
      :margin="[20,20]"
      filename="尽调表"
      :pdf-quality="2"
      :manual-pagination="false"
      pdf-format="a4"
      pdf-orientation="landscape"
    >
      <section
        slot="pdf-content"
        style="padding:40px;"
      >
        <!-- PDF Content Here -->
        <look-info-print
          :detail-data="detailData"
          :setting-list="settingList"
        />
      </section>
    </vue-html2pdf>
    <!-- 打印立项审批表 -->
    <vue-easy-print
      v-if="detailData"
      ref="printApproval"
      table-show
    >
      <!-- 你自己编写打印的模板  -->
      <template slot-scope="func">
        <div id="print-template">
          <approval-print
            :detail-data="detailData"
            :get-chinese-number="func.getChineseNumber"
          />
        </div>
      </template>
    </vue-easy-print>
  </div>
</template>
<script>
import {
  selfProjectList,
  projectInfoDetail,
  projectInfoDelete,
  submitResearch,
  returnResearch,
  applyResolution,
  lookInfoList
} from '@/api/projectInformation'
import { lookInfoSet } from '@/api/printSetting'
import { lookInfoPrintData } from '@/assets/js/commonFun'
import VueHtml2pdf from 'vue-html2pdf'
export default {
  name: 'ProjectInfoManagement',
  components: {
    AuditDialog: () => import('../../modules/auditDialog'),
    StartMeetingDialog: () => import('../../modules/startMeetingDialog'),
    RequirementListDialog: () => import('../../modules/requirementListDialog'),
    ProjectApprovalDialog: () =>
      import('../../modules/projectApprovalDialog.vue'),
    ApprovalPrint: () => import('../../modules/approvalPrint.vue'),
    LookInfoPrint: () => import('../../modules/lookInfoPrint.vue'),
    ReturnLookInfoDialog: () =>
      import('../../modules/returnLookInfoDialog.vue'),
    VueHtml2pdf
  },
  data() {
    return {
      userInfo: null,
      // 当前id
      currentId: '',
      detailData: null,
      // 是否关联项目课题
      relatedTopics: false,
      showSearch: true,
      // 总条数
      total: 0,
      // 流程审批测试表格数据
      tableList: [],
      categoryOption: [
        { id: 1, value: 0, label: '全部立项' },
        { id: 2, value: 1, label: '我创建的' },
        { id: 3, value: 2, label: '我调研的' }
      ],
      // $comment字典
      statusOptions: [
        { id: 1, value: -1, label: '全部' },
        { id: 2, value: 0, label: '草稿' },
        { id: 3, value: 1, label: '调研中' },
        { id: 4, value: 2, label: '评估中' },
        { id: 5, value: 3, label: '决议审批中' },
        { id: 6, value: 4, label: '不予立项' },
        { id: 7, value: 5, label: '暂时搁置' },
        { id: 8, value: 6, label: '同意立项' },
        // { id: 9, value: 7, label: '立项审批中' },
        // { id: 10, value: 8, label: '拒绝' },
        // { id: 11, value: 9, label: '通过' },
        { id: 12, value: 10, label: '已立项审批' }
        // { id: 13, value: 11, label: '已回退' }
      ],
      dateRange: '',
      // 查询参数
      queryParams: {
        pager: {
          skip: 1,
          limit: 10
        },
        info_status: -1,
        select_type: 0,
        apply_type_id: '',
        project_type_id: '',
        select_str: '',
        start_time: '',
        end_time: '',
        if_source: 0
      },
      projectTypeOptions: [],
      settingList: [],
      allLookInfoList: []
    }
  },
  computed: {
    pdfOptions() {
      return {
        margin: [5, 5],
        filename: `${this.detailData.project_name}-尽调表`
      }
    }
  },
  // 返回后是否刷新列表
  beforeRouteEnter(to, from, next) {
    console.log(to, from, next)
    to.params.refresh = from.params.refresh

    next()
  },
  activated: function() {
    if (this.$route.params.refresh) {
      this.getList()
    }
  },
  created() {
    var if_source = this.$route.query.research
      ? Number(this.$route.query.research)
      : 0
    if (if_source) {
      this.queryParams.if_source = 1
      this.queryParams.select_type = 2
      this.queryParams.info_status = 1
    }

    // 获取当前登录人所在部门的信息
    this.userInfo = this.$store.getters.userInfo
    this.getSysAllDic()
    this.getList()
  },
  methods: {
    getSysAllDic() {
      let allDic = this.$store.getters.sysDic()
      if (!allDic) {
        this.$store.dispatch('sys/getSysAllDic').then((data) => {
          allDic = data
        })
      }
      this.projectTypeOptions = allDic['project_type']
      console.log(this.projectTypeOptions)
    },
    // 打印尽调表
    async printLookInfo(row) {
      let settingArr = []
      this.detailData = row
      // 获取打印设置初始数据
      const res1 = await lookInfoSet({ dictType: 'jd_print_type' })
      if (res1.code === 200) {
        const obj = res1.data[0]
        if (obj && obj.dict_val) {
          settingArr = JSON.parse(obj.dict_val) || []
          // // 找到打印所需部门、并找出要打印的值
          this.settingList = lookInfoPrintData(
            settingArr,
            row.department_research
          )
        } else {
          this.$message({ type: 'error', message: '打印尽调数据出错' })
        }
      } else {
        this.$message({ type: 'error', message: '打印尽调设置服务出错' })
      }

      setTimeout(() => {
        this.$refs.printLookInfo.print()
      }, 50)
    },
    // 打印立项审批表
    async printApproval(row) {
      const res = await projectInfoDetail({ id: row.id })
      if (res.code === 200) {
        this.detailData = res.data
      }
      setTimeout(() => {
        this.$refs.printApproval.print()
      }, 50)
    },
    // 创建立项项目
    createProject() {
      if (this.relatedTopics) {
        this.$refs.requirementListDialog.open()
      } else {
        this.$router.push({
          name: 'createEdit'
        })
      }
    },
    // 导出尽调表
    async exportLookInfo(row) {
      let settingArr = []
      this.detailData = row
      // 获取打印设置初始数据
      const res1 = await lookInfoSet({ dictType: 'jd_print_type' })
      if (res1.code === 200) {
        const obj = res1.data[0]
        if (obj && obj.dict_val) {
          settingArr = JSON.parse(obj.dict_val) || []
          // // 找到打印所需部门、并找出要打印的值
          this.settingList = lookInfoPrintData(
            settingArr,
            row.department_research
          )
        } else {
          this.$message({ type: 'error', message: '打印尽调数据出错' })
        }
      } else {
        this.$message({ type: 'error', message: '打印尽调设置服务出错' })
      }

      setTimeout(() => {
        this.$refs.html2Pdf.generatePdf()
      }, 50)
    },
    dateRangeChang(val) {
      console.log(val)
      if (val && val.length) {
        this.queryParams.start_time = val[0]
        this.queryParams.end_time = val[1]
      } else {
        this.queryParams.start_time = ''
        this.queryParams.end_time = ''
      }
      this.getList()
    },
    // categoryChange(val) {
    //   console.log(val)
    //   const item = this.categoryOption.find(p => p.value === val)
    //   if (item) {
    //     if (item.value === 0) {
    //       this.queryParams.select_str = ''
    //     } else {
    //       this.queryParams.select_str = item.label
    //     }
    //   }
    //   this.queryParams.pager.skip = 1
    //   this.getList()
    // },
    filterChange() {
      this.queryParams.pager.skip = 1
      this.getList()
    },
    /** 查询流程审批测试列表 */
    getList() {
      selfProjectList(this.queryParams).then((response) => {
        const listData = response.data.data || []
        this.total = response.data.total
        listData.forEach((item) => {
          // 是否为创建人
          if (item.creator_id === this.userInfo.user?.id) {
            item.isCreator = true
          } else {
            item.isCreator = false
          }
          // 是否参与调研，是否提交了调研报告
          if (
            !item.department_research ||
            item.department_research.length === 0
          ) {
            item.isJoin = false
            item.isSubmit = false
          } else {
            const fitem = item.department_research.find(
              (p) => p.department_id === this.userInfo.user?.department?.id
            )
            if (fitem) {
              item.isJoin = true
              if (fitem.if_commit === 1) {
                item.isSubmit = true
              } else {
                item.isSubmit = false
              }
            } else {
              item.isJoin = false
            }
          }
        })
        this.tableList = listData
        console.log(this.tableList, listData)
      })
    },
    // 启动调研
    startResearch(row) {
      console.log('启动调研')
      const datas = { id: row.id }
      submitResearch(datas).then((res) => {
        if (res.code === 200) {
          this.$message.success('启动成功')
          this.getList()
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    // 表单重置
    reset() {
      this.dateRange = ''
      this.queryParams = {
        pager: {
          skip: 1,
          limit: 10
        },
        info_status: -1,
        select_type: 0,
        apply_type_id: '',
        select_str: '',
        start_time: '',
        end_time: '',
        if_source: 0
      }
    },
    /** 搜索按钮操作 */
    handleSearch() {
      this.queryParams.pager.skip = 1
      console.log(this.dateRange)
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset()
      this.handleSearch()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({
        name: 'createEdit',
        query: {
          projectId: row.id
        }
      })
    },
    /** 提交报告操作 */
    submitReport(row) {
      this.$router.push({
        name: 'projectDetail',
        query: {
          projectId: row.id,
          tabs: 'subReport'
        }
      })
    },
    /** 审批按钮操作 */
    handleAudit(row) {
      this.currentId = row.id
      this.$refs.auditDialog.open()
    },
    // 提交立项审批
    submitProjectApproval(row) {
      this.$router.push({
        name: 'submitApproval',
        query: {
          projectId: row.id,
          types: 1
        }
      })
    },
    // 发起会议
    startMeeting(row) {
      // this.$refs.startMeetingDialog.open()
      // this.$message({
      //   type: 'warning',
      //   message: '会议模块还在开发中'
      // })
      this.$comFun.goMeetingCreate(1, { name: row.project_name, id: row.id })
    },
    // 回退调研
    returnResearchOperation(row) {
      if (row.info_status === 2) {
        this.$refs.returnLookDialog.open(row)
      } else {
        const dat = { id: row.id }
        returnResearch(dat).then((res) => {
          if (res.code === 200) {
            if (row.info_status === 2) {
              this.$message.success('回退成功')
            } else if (row.info_status === 5) {
              this.$message.success('启动成功')
            }
            this.getList()
          } else {
            this.$message.error(res.msg)
          }
        })
      }
    },
    // 申请决议
    applyResolutionOperation(row) {
      const dat = { id: row.id }
      applyResolution(dat).then((res) => {
        if (res.code === 200) {
          this.$message.success('申请决议成功')
          this.getList()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    evaluationSuccess() {
      this.currentId = ''
      this.getList()
    },
    backSuccess() {
      this.getList()
    },
    tableRowClick(row, column, event) {
      if (column.label === '操作') return
      this.$router.push({
        name: 'projectDetail',
        query: {
          projectId: row.id
        }
      })
    },
    tableCellStyle(row) {
      if (row.column.label === '操作') {
        return
      } else {
        return 'cursor: pointer'
      }
    },
    details(row) {
      this.$router.push({
        name: 'projectDetail',
        query: {
          projectId: row.id
        }
      })
    },
    // 立项审批操作
    projectApprovalOperation(row) {
      this.currentId = row.id
      this.$refs.projectApprovalDialog.open()
    },
    projectApprovalSuccess() {
      this.currentId = ''
      this.getList()
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const that = this
      const ids = row.id || ''
      this.$confirm('删除自研立项信息后，数据将不可恢复，确认删除？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          projectInfoDelete({ id: ids })
        })
        .then(() => {
          if (
            that.total > that.tableList.length &&
            that.tableList.length === 1
          ) {
            that.queryParams.pager.skip = that.queryParams.pager.skip - 1
          }
          this.getList()
        })
        .catch(function() {})
    }
  } // methods结束
}
</script>

<style lang="scss" scoped>
.view-container {
  padding-top: 110px;
  box-sizing: border-box;
  .filter-form {
    ::v-deep .el-input {
      width: 160px;
    }
  }
}
</style>
